import { useMemberStore } from "@/store/member"

/**
 * 
 * @param fn 需要节流执行的函数
 * @param time time时间内只允许执行一次
 */
export const throttle = (fn: () => void, time: number) => {
  let oldDate = 0
  return function () {
    let newdate = Number(new Date())
    if (newdate - oldDate >= time) {
      fn()
      oldDate = newdate
    }
  }
}


/**
 * 上传图片
 * @param distinguish 判断当前是预览还是上传图片
 */
export const onChooseImage = (distinguish: string) => {
  const memberStore = useMemberStore()
  if (distinguish === 'preview') {
    let imgsArray = []
    imgsArray[0] = memberStore.profile.avatar
    uni.previewImage({
      current: 0,
      urls: imgsArray,
    })
  } else if (distinguish === 'avatar') {
    // 从本地相册选择图片或使用相机拍照
    uni.chooseImage({
      count: 1,//默认9张
      sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
      success: (img) => {
        // console.log('[ img ] >', img)
        uni.uploadFile({
          url: 'https://pcapi-xiaotuxian-front-devtest.itheima.net/member/profile/avatar',
          filePath: img.tempFilePaths[0],
          name: 'file', // 上传图片类型
          header: {
            Authorization: memberStore.profile.token
          },
          success: (file) => {
            // console.log('[ file ]-31', file)
            const data = JSON.parse(file.data)
            // console.log('[ data ]-33', data)
            if (data.code !== '1') return uni.showToast({ icon: 'error', title: '上传失败！' })
            // 提示正在上传中
            uni.showLoading({
              title: '上传中',
              mask: true
            })
            // 将图片保存到仓库并进行更新操作
            memberStore.updateAvatar(data.result.avatar)
            // 上传成功
            setTimeout(() => {
              uni.showToast({ title: '上传成功', icon: 'success' })
            }, 1000)
          },
          complete: () => {
            setTimeout(() => {
              uni.hideLoading()
            }, 1000)
          },
        })
      },
    })
  }
}

